var path = require('path');
var fs = require('fs');

var filepath = path.resolve("filetest/config.ini");


/*

path.dirname
path.basename
path.extname

fs.exists(file_path,function(exists){}}

fs.stat(file_path,function(err,stats){

	stats.isFile()
	stats.isDirectory()
	err.errno


}}

fs.open(filepath,'r',function(err,fd){

})


*/


function getPathInfo(file_path){

    console.log("===========文件信息===========");
    console.log("文件目录："+path.dirname(file_path));
    console.log("文件全名："+path.basename(file_path));
    console.log("文件名："+path.basename(file_path,path.extname(file_path)));
    console.log("文件后缀名："+path.extname(file_path));
    fs.exists(file_path,function(exists){
    	console.log("这个文件存在吗："+(exists ? "存在":"不存在"));

		if(exists){
			
			

		}

	});

    fs.stat(file_path,function(err,stats){
        if(stats){
        console.log("===================");
        console.log("是文件吗："+ (stats.isFile() ? "是":"不是"));
        console.log("是文件夹吗："+ (stats.isDirectory() ? "是":"不是"));
        console.log("===================");
        console.log(stats);
        }else{
            console.log("ERROR:code "+err.errno);
		}
    });

}
getPathInfo(filepath);



//流式文件读取
/*
fs.open(filepath,'r',function(err,fd){
	
	if(err){ throw err}
	console.log('========以下是文件描述符===============');
	console.log(fd);
	
	var readBuffer = new Buffer.alloc(1024);
		bufferOffset = 0,
		bufferLength = readBuffer.length,
		filePosition = 1;

	fs.read(fd,readBuffer,bufferOffset,bufferLength,filePosition,function(err,readBytes){
		
		if(err){ throw err }
		console.log('已经读取：' + readBytes + '字节');
		if(readBytes > 0){
			console.log(readBuffer.slice(0,readBytes));
		}

	});

});*/




function WriteStream(filepath,cnt){

	var ws = fs.createWriteStream(filepath);

	ws.on("open",function(){
		console.log("写入流打开了\n");
	});

	ws.on("close",function(){
		console.log("写入流关闭了\n");
	})

	ws.write(cnt);

	ws.end();
}

WriteStream("testWriteStream.txt","通过可写流写入 文件 内容 \n 通过可写流写入文件内容/n通过可写流写入文件内容通过可写流写入文件内容");



//复制文件
function copyFileByStream(source_file_path, copy_file_path){

	var rs = fs.createReadStream(source_file_path);

	var ws = fs.createWriteStream(copy_file_path);

	rs.on("open",function(){
		console.log("读取流打开了\n");
	});

	rs.on("close",function(){	
		ws.end();
		console.log("读取流关闭了\n");
	});


	rs.on("data",function(data){
		ws.write(data);
	});

	ws.on("open",function(){
		console.log("写入流打开：");
	});

	ws.on("close",function(){
		console.log("写入流关闭：");
	});

}


copyFileByStream("images/乡下26.jpg", "img/xiang.jpg");



